package com.example.tijianserver.service;

import com.example.tijianserver.mapper.UsersMapper;
import com.example.tijianserver.pojo.Users;

import com.example.tijianserver.response.TijianException;
import com.example.tijianserver.response.TijianExceptionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.example.tijianserver.utils.MD5Util.MD5Encrypt;

@Service
public class UsersServiceImpl implements UsersService {
    @Autowired
    UsersMapper usersMapper;
    //处理登录业务
    /*
    调用mapper中的方法查询该用户是否存在，存在返回该用户数据，不存在报错
     */
    @Override
    public Users login(Users users){

        Users user=usersMapper.selectByPrimaryKey(users.getUserId());

        if((user!=null) && (users.getPassword().equals(user.getPassword()))){
            return user;
        }else {
            //不存在抛出异常
            throw new TijianException(TijianExceptionEnum.PHONE_OR_PASSWORD_IS_WRONG);
        }
    }
    //注册
   @Override
    public int register(Users users) {
        // 检查用户名是否已存在
        Users user = usersMapper.selectByPrimaryKey(users.getUserId());
        if (user != null) {
            throw  new TijianException(TijianExceptionEnum.REGISTER_FAILED); // 用户名已存在
        }else {
            // 插入新用户
            return usersMapper.insertSelective(users);
        }
    }

    //找回密码--根据userId查询信息
    @Override
    public Users forgot(Users users) {
        Users user = usersMapper.selectByPrimaryKey(users.getUserId());
        if(user==null) {           //不存在抛出异常
            throw new TijianException(TijianExceptionEnum.KDC_ERR_C_PRINCIPAL_UNKNOWN);//用户名不存在
        }
        //判断身份证是否相同
        if (users.getIdentityCard().equals(user.getIdentityCard())){
            return user;
        }else {
            throw new TijianException(TijianExceptionEnum.FORGOT_FAILED);
        }
    }

    //删除
    @Override
    public int deleteUser(String userId) {
        // 删除用户
        int result = usersMapper.deleteByPrimaryKey(userId);
        return result;
    }

    @Override
    public boolean updatePassword(Users users) {
        int update = usersMapper.updateByPrimaryKeySelective(users);
        if (update>0){
            return true;
        }else {
            //不存在抛出异常
            throw new TijianException(TijianExceptionEnum.PHONE_OR_PASSWORD_IS_WRONG);
        }

    }


}
